package com.oocl.RTManageServer.manager.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import com.oocl.RTManageServer.manager.RTServerManager;
import com.oocl.RTManageServer.responser.HttpResponser;
import com.oocl.constant.ProtocolType;
import com.oocl.pojo.Protocol;
import com.oocl.util.JsonUtil;
import com.oocl.util.ResourceCloser;

public class RTServerManagerImpl implements RTServerManager{
	
	private HttpResponser responser;
	
	public RTServerManagerImpl(HttpResponser responser) {
		this.responser = responser;
	}

	@Override
	public void processStart() {
		Protocol pro1 = new Protocol();
//		pro1.setType(ProtocolType.START_RT);
		pro1.setTime(new Date());
		Protocol pro2 = sendRequest(pro1);
		System.out.println(pro2);
	}

	@Override
	public void processStop() {
		Protocol pro1 = new Protocol();
//		pro1.setType(ProtocolType.STOP_RT);
		pro1.setTime(new Date());
		Protocol pro2 = sendRequest(pro1);
		System.out.println(pro2);
	}


	@Override
	public void getServerTime() {
		Protocol pro1 = new Protocol();
//		pro1.setType(ProtocolType.GET_RT_TIME);
		pro1.setTime(new Date());
		Protocol pro2 = sendRequest(pro1);
		System.out.println(pro2);
	}
	
	private Protocol sendRequest(Protocol pro){
		Protocol protocol = null;
		Socket socket = null;
		BufferedReader reader = null;
		PrintWriter writer = null;
		try {
			socket = new Socket("127.0.0.1", 6666);
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			writer = new PrintWriter(socket.getOutputStream());
			writer.println(JsonUtil.toJsonObject(pro).toString());
			writer.flush();
			
			String line = reader.readLine();
			protocol = JsonUtil.toProtocol(new JSONObject(line.trim()));
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			ResourceCloser.release(writer, reader, socket, null);
		}
		return protocol;
	}

}
